package com.wonghiu.framework.registry.zk;

import com.wonghiu.framework.cluster.directory.imp.ServiceDirectory;
import com.wonghiu.framework.cluster.loadbalance.LoadBalance;
import com.wonghiu.framework.common.extention.ExtensionLoader;
import com.wonghiu.framework.common.factory.SingletonFactory;
import com.wonghiu.framework.exchange.HRpcRequest;
import com.wonghiu.framework.registry.ServiceDiscovery;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Author wonghiu
 * @Date 2021/8/10 19:52
 * @Version 1.0.1
 */
@Slf4j
public class ZkServiceDiscoveryImp implements ServiceDiscovery {
    private final LoadBalance loadBalance;
    private ServiceDirectory serviceDirectory;

    public ZkServiceDiscoveryImp() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("consist");
        this.serviceDirectory = SingletonFactory.getInstance(ServiceDirectory.class);
    }

    @Override
    public InetSocketAddress lookupService(HRpcRequest rpcRequest) {
        List<String> serviceUrlList = serviceDirectory.getServiceUrlList(rpcRequest);
        // load balancing
        String targetServiceUrl = loadBalance.selectServiceAddress(serviceUrlList, rpcRequest);
        log.info("Successfully found the service address:[{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return new InetSocketAddress(host, port);
    }
}